#import "MainViewController.h"
#import "Database.h"
#import "Model.h"

@implementation MainViewController
@synthesize photoButton;
@synthesize cameraButton;
@synthesize photo;
@synthesize playButton;
@synthesize recordButton;
@synthesize stopButton;

- (void)viewDidLoad {
    [super viewDidLoad];
	self.view.backgroundColor = [UIColor whiteColor];
	
	recordButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[recordButton addTarget:self action:@selector(recordAudio:)forControlEvents:UIControlEventTouchUpInside];
	[recordButton setTitle:@"Record" forState:UIControlStateNormal];
	recordButton.frame = CGRectMake(10, 10, 100, 50);
	[self.view addSubview:recordButton];
	
	playButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[playButton addTarget:self action:@selector(playAudio:)forControlEvents:UIControlEventTouchUpInside];
	[playButton setTitle:@"Play" forState:UIControlStateNormal];
	playButton.frame = CGRectMake(10, 60, 100, 50);
	[self.view addSubview:playButton];
	
	stopButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[stopButton addTarget:self action:@selector(stop:)forControlEvents:UIControlEventTouchUpInside];
	[stopButton setTitle:@"Stop" forState:UIControlStateNormal];
	stopButton.frame = CGRectMake(10, 110, 100, 50);
	[self.view addSubview:stopButton];
	
	photoButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[photoButton addTarget:self action:@selector(pickImage:)forControlEvents:UIControlEventTouchUpInside];
	[photoButton setTitle:@"Photo" forState:UIControlStateNormal];
	photoButton.frame = CGRectMake(10, 160, 100, 50);
	[self.view addSubview:photoButton];
	
	cameraButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[cameraButton addTarget:self action:@selector(pickImageCamera:)forControlEvents:UIControlEventTouchUpInside];
	[cameraButton setTitle:@"Camera" forState:UIControlStateNormal];
	cameraButton.frame = CGRectMake(10, 210, 100, 50);
	[self.view addSubview:cameraButton];
	
	Database *database = [Database getDatabase];
	NSData *imageData = [database findLastImage];
	if (imageData == nil) {
		photo = [[UIImageView alloc] initWithFrame:CGRectMake(110,10 , 200, 200)];
		photo.image = [UIImage imageNamed:@"none.jpg"];
		[self.view addSubview:photo];
	}else {
		UIImage *image = [UIImage imageWithData:imageData];
		photo = [[UIImageView alloc] initWithFrame:CGRectMake(110,10 , 200, 200)];
		photo.image = image;
		[self.view addSubview:photo];
	}

	
	//playButton.enabled = NO;
	stopButton.enabled = NO;
	NSArray *dirPaths;
	NSString *docsDir;
	dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	docsDir = [dirPaths objectAtIndex:0];
	NSString *soundFilePath = [docsDir
							   stringByAppendingPathComponent:@"sound.caf"];
	
	NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
	NSDictionary *recordSettings = [NSDictionary 
									dictionaryWithObjectsAndKeys:
									[NSNumber numberWithInt:AVAudioQualityMin],
									AVEncoderAudioQualityKey,
									[NSNumber numberWithInt:16], 
									AVEncoderBitRateKey,
									[NSNumber numberWithInt: 2], 
									AVNumberOfChannelsKey,
									[NSNumber numberWithFloat:44100.0], 
									AVSampleRateKey,
									nil];
	NSError *error = nil;
	audioRecorder = [[AVAudioRecorder alloc]
					 initWithURL:soundFileURL
					 settings:recordSettings
					 error:&error];
	if (error)
	{
		NSLog(@"error: %@", [error localizedDescription]);
	} else {
		[audioRecorder prepareToRecord];
	}
}
-(void)pickImage:(id)sender{
	UIImagePickerController *picker = [[UIImagePickerController alloc] init];
	picker.delegate = self;
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
		picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
	}
	picker.allowsEditing = YES;
	[self presentModalViewController:picker animated:YES];
}
-(void)pickImageCamera:(id)sender{
	UIImagePickerController *picker = [[UIImagePickerController alloc] init];
	picker.delegate = self;
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
		picker.sourceType = UIImagePickerControllerSourceTypeCamera;
	}
	picker.allowsEditing = YES;
	[self presentModalViewController:picker animated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
	if (!image) image = [info objectForKey:UIImagePickerControllerOriginalImage];
	if (!image) return;
	photo.image = image;
	
	
	Database *database = [Database getDatabase];
	NSFetchedResultsController *dataFetchedResultsController = database.dataFetchedResultsController;
	NSManagedObjectContext *context = [dataFetchedResultsController managedObjectContext];	
	NSEntityDescription *entity = [[dataFetchedResultsController fetchRequest] entity];	
	
	NSManagedObject *data = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
	NSData *imageData = UIImagePNGRepresentation(image);
	[data setValue:imageData forKey:@"data"];
	
	[database saveChanges];
	
	[self dismissModalViewControllerAnimated:YES];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void) recordAudio:(id)sender{
	NSLog(@"recordAudio..");
	if (!audioRecorder.recording)
	{
		//playButton.enabled = NO;
		stopButton.enabled = YES;
		recordButton.enabled = NO;
		[audioRecorder record];
	}
}
-(void) playAudio:(id)sender{
	if (!audioRecorder.recording)
    {
		stopButton.enabled = YES;
		recordButton.enabled = NO;
		//playButton.enabled = NO;
		
        if (audioPlayer)
			[audioPlayer release];
        NSError *error;
		Database *database = [Database getDatabase];
		NSData *voiceData = [database findLastVoice];
		audioPlayer = [[AVAudioPlayer alloc] initWithData:voiceData error:&error];
		
        audioPlayer.delegate = self;
		
        if (error)
			NSLog(@"Error: %@", 
				  [error localizedDescription]);
        else
			[audioPlayer play];
	}
}
-(void) stop:(id)sender{
	stopButton.enabled = NO;
    recordButton.enabled = YES;
	
    if (audioRecorder.recording)
    {
		[audioRecorder stop];
		//store core data
		NSData *voiceData = [[NSData alloc] initWithContentsOfURL:audioRecorder.url];
		
		Database *database = [Database getDatabase];
		NSFetchedResultsController *dataFetchedResultsController = database.voiceFetchedResultsController;
		NSManagedObjectContext *context = [dataFetchedResultsController managedObjectContext];	
		NSEntityDescription *entity = [[dataFetchedResultsController fetchRequest] entity];	
		
		NSManagedObject *data = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
		[data setValue:voiceData forKey:@"voice"];
		[database saveChanges];
		
    } else if (audioPlayer.playing) {
		[audioPlayer stop];
    }
}
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player 
					  successfully:(BOOL)flag
{
	recordButton.enabled = YES;
	stopButton.enabled = NO;
}
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player 
								error:(NSError *)error
{
	NSLog(@"Decode Error occurred");
}
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder 
						  successfully:(BOOL)flag
{
}
-(void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder 
								  error:(NSError *)error
{
	NSLog(@"Encode Error occurred");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
    [super viewDidUnload];
}

- (void)dealloc {
    [super dealloc];
}

@end
